package com.bawei.image.glide

import android.content.Context
import android.os.Environment
import com.bumptech.glide.Glide
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.LibraryGlideModule
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
import java.io.InputStream

/**
 * Author: Jason Zhang
 * Date: 2024/4/23
 * Desc: 利用OKHttpClient来设置图片网络缓存
 */

@GlideModule
class OkHttpModule : LibraryGlideModule(){

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        var okhttpBuilder = OkHttpClient.Builder()
        //获取外部存储目录
        var externalStorageDir = Environment.getExternalStorageDirectory()
        if(externalStorageDir.exists()){
            var cacheDir = "${externalStorageDir.absolutePath}/cacheImage"
            var cacheFile = File(cacheDir)
            if(!cacheFile.exists()){
                cacheFile = File(cacheDir)
            }
            //设置缓存文件大小
            okhttpBuilder.cache(Cache(cacheFile, 250 * 1024 * 1024))
        } else {
            var appCacheDir = "${context.externalCacheDir?.absolutePath}/cacheImage"
            var cacheFile = File(appCacheDir)
            if(!cacheFile.exists()){
                cacheFile = File(appCacheDir)
            }
            //计算一下缓存文件大小
            var cacheSize = 50 * 1024 * 1024L
            context.externalCacheDir?.totalSpace?.let {
                cacheSize = it / 4L
            }
            okhttpBuilder.cache(Cache(cacheFile, cacheSize))
        }

        //给Glide注册新的OKHttpClient
        registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(okhttpBuilder.build()))

    }


}